/**
 * AI聊天API服务
 */

const API_BASE_URL = 'http://localhost:8080/api/v1';

/**
 * 发送聊天消息（流式）
 * @param {Object} messageData - 消息数据
 * @param {Function} onChunk - 接收到数据块时的回调
 * @param {Function} onComplete - 完成后回调
 * @param {Function} onError - 错误回调
 */
export async function sendChatMessage(messageData, { onChunk, onComplete, onError, signal } = {}) {
  try {
    const response = await fetch(`${API_BASE_URL}/chat/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'Connection': 'keep-alive',
      },
      body: JSON.stringify(messageData),
      signal,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        onComplete?.();
        break;
      }

      // 解码数据
      buffer += decoder.decode(value, { stream: true });
      
      // 处理多个数据行
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 保留最后一个不完整的行

      for (const line of lines) {
        const trimmedLine = line.trim();
        if (trimmedLine.startsWith('data:')) {
          try {
            const jsonStr = trimmedLine.slice(5).trim();
            if (jsonStr) {
              const data = JSON.parse(jsonStr);
              onChunk?.(data);
            }
          } catch (e) {
            console.error('解析SSE数据失败:', e);
          }
        }
      }
    }
  } catch (error) {
    // 若为主动中断，不视为异常提示
    if (error && error.name === 'AbortError') {
      onError?.(error);
      return;
    }
    console.error('API调用失败:', error);
    onError?.(error);
  }
}

/**
 * 取消正在进行的对话
 */
export async function cancelChatRequest({ requestId, sessionId } = {}) {
  if (!requestId && !sessionId) {
    return Promise.resolve();
  }

  const payload = {};
  if (requestId) payload.requestId = requestId;
  if (sessionId) payload.sessionId = sessionId;

  const res = await fetch(`${API_BASE_URL}/chat/cancel`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': '*/*',
    },
    body: JSON.stringify(payload),
  });

  if (res.ok || res.status === 404) {
    return res;
  }
  throw new Error('取消对话失败');
}

/**
 * ---------------- 会话相关API ----------------
 */

/**
 * 获取用户会话列表
 */
export async function fetchUserSessions(userId) {
  const res = await fetch(`${API_BASE_URL}/sessions/user/${encodeURIComponent(userId)}`, {
    method: 'GET',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
  });
  if (!res.ok) throw new Error('获取会话列表失败');
  return res.json();
}

/**
 * 创建会话
 */
export async function createSession({ userId, sessionName, sessionType }) {
  const formData = new URLSearchParams();
  formData.set('userId', userId);
  formData.set('sessionName', sessionName);
  formData.set('sessionType', sessionType);

  const res = await fetch(`${API_BASE_URL}/sessions`, {
    method: 'POST',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
    body: formData.toString(),
  });
  if (!res.ok) throw new Error('创建会话失败');
  return res.json();
}

/**
 * 删除会话
 */
export async function deleteSession(sessionId, userId) {
  const url = `${API_BASE_URL}/sessions/${encodeURIComponent(sessionId)}?userId=${encodeURIComponent(userId)}`;
  const res = await fetch(url, {
    method: 'DELETE',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
  });
  if (!res.ok) throw new Error('删除会话失败');
  return res.json();
}

/**
 * 置顶/取消置顶
 */
export async function pinSession(sessionId, pinned) {
  const formData = new URLSearchParams();
  formData.set('pinned', String(pinned));
  const res = await fetch(`${API_BASE_URL}/sessions/${encodeURIComponent(sessionId)}/pin`, {
    method: 'PUT',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
    body: formData.toString(),
  });
  if (!res.ok) throw new Error('置顶会话失败');
  return res.json();
}

/**
 * 会话详情
 */
export async function fetchSessionDetail(sessionId) {
  const res = await fetch(`${API_BASE_URL}/sessions/${encodeURIComponent(sessionId)}`, {
    method: 'GET',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
  });
  if (!res.ok) throw new Error('获取会话详情失败');
  return res.json();
}

/**
 * 会话消息记录
 */
export async function fetchSessionMessages(sessionId, page = 1, size = 20) {
  const url = `${API_BASE_URL}/sessions/${encodeURIComponent(sessionId)}/messages?page=${page}&size=${size}`;
  const res = await fetch(url, {
    method: 'GET',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
  });
  if (!res.ok) throw new Error('获取会话消息失败');
  return res.json();
}

/**
 * 清空会话记录
 */
export async function clearSessionMessages(sessionId) {
  const url = `${API_BASE_URL}/sessions/${encodeURIComponent(sessionId)}/clear`;
  const res = await fetch(url, {
    method: 'DELETE',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
  });
  if (!res.ok) throw new Error('清空会话记录失败');
  return res.json();
}

/**
 * ---------------- MCP 服务管理 ----------------
 * 统一以 /mcp/tools 接口为数据源
 */
export async function fetchMcpTools() {
  const res = await fetch(`${API_BASE_URL}/mcp/tools`, {
    method: 'GET',
    headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' },
  });
  if (!res.ok) throw new Error('获取MCP工具失败');
  return res.json();
}
